
#include<iostream>
#include<cstdio>
#include<string>
#include<unistd.h>
#include<fcntl.h>
using namespace std;


void SetNonBlock(int fd)
{
    int fl = fcntl(fd,F_GETFL);//取出当前文件描述符的属性
    if(fl < 0)
    {
        perror("fcntl fail");
        return;
    }
    fcntl(fd,F_SETFL,fl|O_NONBLOCK);//设置为非阻塞
}

//非阻塞式等待
int main()
{
    string tips = "Please Enter# ";
    char buffer[1024];
    SetNonBlock(0);
    while(true)
    {
        ::write(0,tips.c_str(),tips.size());//写到标准输入
        int n = ::read(0,buffer,sizeof(buffer));
        if(n >0)
        {
            buffer[n] = 0;
            cout <<  "echo# " <<buffer << endl;
        }
        else if(n == 0)
        {
            cout << "read fail end!" << endl;
            break;
        }
        else //失败的不同类型
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK) //表示底层资源未就绪
            {
                cout << "底层资源未就绪..." << endl;
            }
            else if(errno == EINTR)
            {
                cout << "信号中断，从头来过.." << endl;
                continue;
            }
            else //失败
              cout << "read error" << n << " errno: "<< errno <<  endl;
        }
        sleep(1);
    }

    return 0;
}



//阻塞式等待
// int main()
// {
//     string tips = "Please Enter# ";
//     char buffer[1024];
//     while(true)
//     {
//         ::write(0,tips.c_str(),tips.size());//写到标准输入
//         int n = ::read(0,buffer,sizeof(buffer));
//         if(n >0)
//         {
//             buffer[n] = 0;
//             cout <<  "echo# " <<buffer << endl;
//         }
//         else
//         {
//             cout << "read error" << endl;
//         }
//     }

//     return 0;
// }

